package com.nowcoder.controller;

import com.nowcoder.model.Comment;
import com.nowcoder.model.EntityType;
import com.nowcoder.model.HostHolder;
import com.nowcoder.service.CommentService;
import com.nowcoder.service.QuestionService;
import com.nowcoder.util.WendaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;

@Controller
public class CommentController {
    private static final Logger logger = LoggerFactory.getLogger(CommentController.class);


    @Autowired
    private CommentService commentService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private QuestionService questionService;

    @RequestMapping(value = {"/addComment"},method = {RequestMethod.POST})
    public String addComment(@RequestParam("questionId")int questionId,
                             @RequestParam("content")String content){
       try {
           Comment comment = new Comment();
           comment.setContent(content);
           if (hostHolder.getUser() != null) {
               comment.setUserId(hostHolder.getUser().getId());
           } else {
//            return "redirect:/reglogin";
               comment.setUserId(WendaUtil.ANONYMOUS_USERID);//如果用户未登录,则是匿名用户
           }
           comment.setCreatedDate(new Date());
           comment.setEntityType(EntityType.ENTITY_QUESTION);
           comment.setEntityId(questionId);

           //这里应该添加事务
           commentService.addComment(comment);//增加评论
           int count = commentService.getCommentCount(comment.getEntityId(),comment.getEntityType());
           questionService.updateCommentCount(comment.getEntityId(),count);
       }catch (Exception e){
           logger.error("增加评论失败" + e.getMessage());
       }
       return "redirect:/question/" + String.valueOf(questionId);//直接跳转到Question页面
    }
}
